package utils.hog;

/*
 * 可以使用 java -Xmx6g ResourceHog 命令来启动该程序
 */
@SuppressWarnings("unused")
public class ResourceHog {
	public static void main(String[] args) throws InterruptedException {
		new MemoryHog().start();
		Thread.sleep(3000);
		new CpuHog().start();
	}

	private static class CpuHog extends Thread {

		@Override
		public void run() {
			System.out.println("CpuHog");
			while (true) {
				for (double i = Double.MAX_VALUE - 1000; i < Double.MAX_VALUE; i++) {
					Math.sqrt(i);
				}
				new Thread().start();
			}
		}
	}

	private static class MemoryHog extends Thread {

		@Override
		public void run() {
			int length = 1024 * 1024 * 1024;
			int[] data = new int[length];

			while (true) {
				// 消耗内存
				try {
					for (int i = 0; i < length; i++) {
						data[i] = i;
					}

					System.out.println(data[length - 1]);
					System.out.println("MemoryHog");
					Thread.sleep(5000l);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
